﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Eqwww.App.Authorize;
using Microsoft.AspNetCore.Mvc;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.App.SystemManage;
using Eqwww.Code;
using Eqwww.Web.Areas.SystemManage.Models.Module;
using AutoMapper;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    [Area("SystemManage")]
    public class ModuleController : ControllerBase
    {
        private ModuleApp _moduleApp;
        private StrategoryApp _strategoryApp;
        private AuthorizeApp _authorizeApp;
        private IMapper _mapper;
        public ModuleController(AuthorizeApp authorizeApp,
            ModuleApp moduleApp,
            StrategoryApp strategoryApp,
            IMapper mapper)
        {
            _moduleApp = moduleApp;
            _authorizeApp = authorizeApp;
            _strategoryApp = strategoryApp;
            _mapper = mapper;
        }

        [AuthFilter]
        public IActionResult Index()
        {
            var currentModuleCode = "SystemManage_Module";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        public IActionResult IndexGridJson()
        {
            var data = _moduleApp.GetList();

            var treeList = new List<TreeGridModel>();
            foreach (var item in data)
            {
                TreeGridModel treeModel = new TreeGridModel();
                bool hasChildren = data.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                treeModel.id = item.Id;
                treeModel.isLeaf = hasChildren;
                treeModel.parentId = item.ParentId;
                treeModel.expanded = hasChildren;
                treeModel.entityJson = item.ToJson();
                treeList.Add(treeModel);
            }
            return Content(treeList.TreeGridJson());
        }

        [AuthFilter]
        public IActionResult Details(string id)
        {
            if (id == null)
            {
                return NotFoundObject();
            }

            var moduleModel = _moduleApp.GetInclude(id);

            if (moduleModel == null)
            {
                return NotFound();
            }

            //ViewData["History"] = _dbLogApp.GetObjectHistory(id, 10);
            ViewData["Strategorys"] = _strategoryApp.GetRelatedStrategoryListByModuleId(id);

            return View(moduleModel);
        }

        [AuthFilter]
        public IActionResult Create()
        {
            /*
            ViewData["CreateUserId"] = new SelectList(_context.Users, "Id", "Id");
            ViewData["DeleteUserId"] = new SelectList(_context.Users, "Id", "Id");
            ViewData["LastUpdateUserId"] = new SelectList(_context.Users, "Id", "Id");
            ViewData["ParentId"] = new SelectList(_context.Sys_Modules, "Id", "Id");
            */
            return View();
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Create([Bind("Code,Name,ParentId,MenuMark,Url,Icon,SortCode,ModuleOpenType,IsSystem")] CreateViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var model = _mapper.Map<ModuleModel>(viewModel);
                return Json(_moduleApp.Create(model));
            }

            return Json(Common.ModelStateErrorResult(ModelState));
        }

        [AuthFilter]
        // GET: SystemManage/Module/Edit/5
        public IActionResult Edit(string id)
        {
            if (id == null)
            {
                return ErrorView("id参数为空");
            }

            var moduleModel = _moduleApp.Get(id);
            if (moduleModel == null)
            {
                return NotFoundObject();
            }
            if (moduleModel.IsSystem == true)
                return ErrorView("系统模块不允许修改");

            var parentModule = _moduleApp.Get(moduleModel.ParentId);

            var viewModel = _mapper.Map<EditViewModel>(moduleModel);
            viewModel.ParentName = parentModule == null ? string.Empty : parentModule.Name;

            return View(viewModel);
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(string id, [Bind("Id,Code,Name,ParentId,MenuMark,Url,Icon,SortCode,ModuleOpenType")] EditViewModel viewModel)
        {
            if (id != viewModel.Id)
            {
                return Error("形参和表参不一致！");
            }
            if (ModelState.IsValid)
            {
                var module = _moduleApp.Get(id);
                _mapper.Map(viewModel, module);
                return Json(_moduleApp.Update(module));
            }
            return Json(Common.ModelStateErrorResult(ModelState));
        }

        public IActionResult TreeCollapse()
        {
            ViewData["Items"] = _moduleApp.GetTreeCollapseItems();
            return View();
        }

        public IActionResult TreeCollapseJson()
        {
            var data = _moduleApp.GetTreeCollapseItems();
            return Content(data.ToJson());
        }

        [HttpPost, ActionName("Delete")]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteConfirmed(string id)
        {
            return Json(_moduleApp.Remove(id));

        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsSystem(string id)
        {
            return Json(_moduleApp.UpdateIsSystem(id, true));
        }

        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public IActionResult UpdateIsNotSystem(string id)
        {
            return Json(_moduleApp.UpdateIsSystem(id, false));
        }
    }
}
